import {allMenus,allroutes} from "./data";

function getAllCheckedKeys(){
    let arr = [];
    allMenus.forEach(item=>{
        arr.push(item.id);
        if(item.children && Array.isArray(item.children)){
           item.children.forEach(sonItem=>{
            arr.push(sonItem.id);
           }) 
        }
    })
    return arr;
}

// 2、根据当前用户的权限，得到对应的菜单

export  function getCurrentMenus() {

    let checkedkeys:string[] =  JSON.parse(sessionStorage.getItem("checkedkeys") as string);// ["1","2-1","2"];    

    if(checkedkeys.length==0){
        checkedkeys = getAllCheckedKeys();
    }

    console.log("获取当前用户菜单：checkedKeys",checkedkeys);
    

    // 循环所有的菜单数据（allMenus），如果id在checkedKeys存在，那么就留下来。

    let currMenus = [];

    // 1、循环外层
    allMenus.forEach(item => {
        if (checkedkeys?.includes(item.id)) {
            // currMenus.push({...item});
            let objMenu = {...item}; 

            if (item.children) {
                objMenu.children = [];
                // 2、循环第二层
                item.children.forEach(sonItem=>{
                    if(checkedkeys.includes(sonItem.id)){
                        objMenu.children.push({...sonItem});
                    }
                })
            }
            currMenus.push(objMenu);
        }

    })

    return currMenus;
}

export function getCurrentRoutes($router){
    console.log("getCurrentRoutes()");
    
    let  checkedkeys:string[] = JSON.parse(sessionStorage.getItem("checkedkeys") as string);
    if(!checkedkeys){
        return ;
    }

    if(checkedkeys.length==0){
        checkedkeys = getAllCheckedKeys();
    }


    // 1、删除所有的路由（权限相关的路由）
    allroutes.forEach(item=>{
        $router.removeRoute(item.name);
    })
    console.log("删除路由后：$router.getRoutes()",$router.getRoutes());

    // 2、
    
    allroutes.forEach(item=>{
        if(checkedkeys?.includes(item.id)){
            $router.addRoute("Admin",{...item});
        }
    })

    console.log("$router.getRoutes()",$router.getRoutes());
    
}